package zcj.stu.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpException;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import zcj.stu.utils.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping("file")
public class CommonController {

    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appsecret}")
    private String appSecret;
    @ResponseBody
    @GetMapping("/wxLogin")
    public Result getOpenid(@RequestParam("code") String code){
        try {
            System.out.println(code);
            System.out.println(appid);
            HttpRequest get = HttpUtil.createGet("https://api.weixin.qq.com/sns/jscode2session?appid=" + appid + "&secret=" + appSecret + "&js_code=" + code + "&grant_type=authorization_code");
            HttpResponse response = get.execute();
            return Result.ok(JSON.parse(response.body()));
        } catch (HttpException e) {
            e.printStackTrace();
            return Result.error();
        }

    }
    @ResponseBody
    @GetMapping("/delete")
    public Result deleteBlogImg(@RequestParam("filename") String filename) {
        File file = new File("D:/img", filename);
        if (file.isDirectory()) {
            return Result.error("错误的文件名称");
        }
        FileUtil.del(file);
        return Result.ok();
    }
    @GetMapping("/download")
    public void download(@RequestParam("filename") String filename, HttpServletResponse response) throws IOException {
        BufferedInputStream inputStream=null;
        BufferedOutputStream outputStream=null;
        try {
            byte[]buff=new byte[1024];
            int len=0;
            inputStream = new BufferedInputStream(new FileInputStream("D:/img/" + filename));
            response.setContentType("image/jpeg");
            outputStream=new BufferedOutputStream(response.getOutputStream());
            while ((len=inputStream.read(buff,0,buff.length))!=-1){
                outputStream.write(buff,0,len);
            }
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            if(inputStream!=null)
            inputStream.close();
            if(outputStream!=null)
            outputStream.close();
        }
    }

    @ResponseBody
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file){

        try {
            //获得扩展名
            String expandName = StrUtil.subAfter(file.getOriginalFilename(),".",true);
            //生成一个随机文件名
            String newFileName = createNewFileName(file.getOriginalFilename());
            file.transferTo(new File("D:/img",newFileName));
            return Result.ok(newFileName);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error();
        }
    }
    private String createNewFileName(String originalFilename) {
        // 获取后缀
        String suffix = StrUtil.subAfter(originalFilename, ".", true);
        // 生成目录
        String name = UUID.randomUUID().toString();
        int hash = name.hashCode();
        int d1 = hash & 0xF;
        int d2 = (hash >> 4) & 0xF;
        // 判断目录是否存在
        File dir = new File("D:/img", StrUtil.format("/tea/{}/{}", d1, d2));
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 生成文件名
        return StrUtil.format("/tea/{}/{}/{}.{}", d1, d2, name, suffix);
    }
}
